// pages/exam/exam.js
var utils = require("../../utils/util")
const app = getApp()
const PAGESIZE = 200
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navBarData: app.globalData.navBarData,
        searchbarData: {
            inputFocus: false,
            searchbarValue: null,
            serchbarConfirm: false,
            loading: false
        },
        insearch: false,
        contestDataset: [],
        registerData: {
            show: false,
        },
        pagenum: 1,
        onlyRegistered: false,
        pullDownRefresh: true,
        enableRefresher: true
    },

    navBack: function (e) {
        app.globalData.contestPageType = ''
        this.setData({
            contestDataset: []
        })
        wx.showTabBar({
            animation: false,
        })
        wx.switchTab({
            url: '/pages/userInf/userInf',
        })
    },

    /**
     * 以下为搜索框相关数据绑定，与事件响应
     */
    searchbarCancleHandler: function (event) {
        this.setData({
            'searchbarData.inputFocus': false,
            'searchbarData.searchbarValue': '',
            'searchbarData.serchbarConfirm': false
        })
        this.searchHandler()
    },
    searchbarFocusHandler: function (event) {
        this.setData({
            insearch: true,
            'searchbarData.serchbarConfirm': true,
        })
    },
    searchbarInputBind: function (event) {
        let input = event.detail.value
        this.setData({
            'searchbarData.searchbarValue': input
        })
        this.searchHandler()
    },
    searchHandler: function (e) {
        let keyword = this.data.searchbarData.searchbarValue || ""
        this.getContestListAndSetDataset(keyword, false)
    },

    /**
     * 搜索所有比赛
     * @param {*} keyword 
     */
    getContestListAndSetDataset: function (keyword) {
        this.setData({
            'searchbarData.loading': true
        })
        let that = this
        let onlyR = this.data.onlyRegistered
        let api = onlyR ? utils.APIS.getParticipatedContest : utils.APIS.searchContest
        utils.request({
            ...api,
            data: {
                pagenum: that.data.pagenum,
                pagesize: PAGESIZE,
                keyword: keyword
            }
        }).then(function (ress) {
            if (ress.data.ret === 0) {
                let contestData = ress.data.items
                if (onlyR) {
                    contestData.forEach(element => {
                        element.registered = true
                    });
                }
                that.setData({
                    contestDataset: contestData
                })
            } else {
                let alertText = "发生未知错误\t错误码：" + ress.data.ret + "\t错误类型：" + ress.data.msg
                console.error(alertText)
                wx.showToast({
                    title: alertText,
                    icon: "error"
                })
            }
        }).catch(function (e) {}).finally(function (e) {
            that.setData({
                'searchbarData.loading': false,
                pullDownRefresh: false
            })
        })
    },


    /**
     * 注册窗口绑定
     */
    contestPasswordBind: function (e) {
        let password = e.detail.value
        this.setData({
            'registerData.password': password
        })
    },
    registerContest: function (e) {
        let that = this
        let password = this.data.registerData.password
        wx.showLoading({
            title: '正在注册',
        })
        let api = utils.APIS.registerContest
        utils.request({
            ...api,
            data: {
                contestid: that.data.registerData.contestid,
                password: password
            }
        }).then(function (res) {
            wx.hideLoading()
            if (res.data.ret == 0) {
                wx.showToast({
                    title: '注册成功',

                }).then(function (e) {
                    that.hideRegisterModal()
                })
                that.setData({
                    [`contestDataset[${that.data.registerData.contestindex}].registered`]: true
                })
            } else {
                wx.hideLoading()
                wx.showToast({
                    icon: "error",
                    title: res.data.msg,
                })
            }
        }).catch(function (e) {}).finally(function (e) {

        })
    },
    hideRegisterModal: function (e) {
        this.setData({
            'registerData.show': false,
            'registerData.password': "",

        })
    },
    openRegister: function (detail) {
        this.setData({
            'registerData.contestid': detail.id,
            'registerData.show': true,
            'registerData.contestindex': detail.index,
            'registerData.public': this.data.contestDataset[detail.index].public
        })
    },
    registerHandler: function (event) {
        let detail = event.currentTarget.dataset
        this.openRegister(detail)
    },

    startContest: function (e) {
        let detail = e.currentTarget.dataset
        let contestData = this.data.contestDataset[detail.index]
        let api = utils.APIS.startContest
        wx.showLoading({
            title: '请稍后',
        })
        utils.request({
            ...api,
            data: {
                contestid: contestData.contestid
            }
        }).then(function (res) {
            wx.hideLoading().catch(function () {})
            if (res.data.ret == 0) {
                if (!res.data.finished) {
                    app.globalData.problemLunchData = {
                        ...contestData,
                        type: 'contest'
                    }
                    wx.navigateTo({
                        url: '/pages/problem/problem',
                    })
                } else {
                    wx.navigateTo({
                        url: '/pages/exam/examfinish/exam-finish',
                    })
                }
            } else {
                wx.showToast({
                    title: '请刷新页面',
                    icon: "error"
                })
            }
        }).catch(function () {
            wx.hideLoading().catch(function () {})
        }).finally(function () {})

    },

    outcomeShow: function (e) {
        let data = JSON.stringify({
            type: "contest",
            contestid: e.currentTarget.dataset.id,
            registered: this.data.contestDataset[e.currentTarget.dataset.index].registered || this.data.onlyRegistered,
            contestname: this.data.contestDataset[e.currentTarget.dataset.index].name
        })
        wx.navigateTo({
            url: '/pages/outcome/outcome?data=' + data,
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.searchHandler()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        utils.initGlobalData(this)
        utils.resetGlobalData()
        if (app.globalData.contestPageType == 'Registered') {
            this.setData({
                onlyRegistered: true
            })
            wx.hideLoading()
        } else {
            this.setData({
                onlyRegistered: false
            })
        }
        this.getContestListAndSetDataset("")
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.setData({
            'searchbarData.inputFocus': false,
            'searchbarData.searchbarValue': '',
            'searchbarData.serchbarConfirm': false
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    pullDownRefresh: function () {
        this.setData({
            pullDownRefresh: true
        })
        this.searchbarCancleHandler()
    },
    enablePullDownRefresh: function (event) {
        this.setData({
            enableRefresher: true
        })
    },
    disablePullDownRefresh: function (event) {
        if (event.detail.scrollTop < 25) {
            this.setData({
                enableRefresher: true
            })
        } else if (this.data.enableRefresher) {
            this.setData({
                enableRefresher: false
            })
        }
    },
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})